package com.example.daytest.exception;

import java.io.*;

/**
 * @author heyu
 * @title: TestException
 * @description:异常测试
 * @date 2021/5/18下午8:05
 */
public class TestException {

  public static void main(String[] args) throws Exception {
    TestException t = new TestException();
    // try-finally
    t.tryfinall();

    // try-with-resource
    t.trywithresource();
  }

  public void tryfinall() throws Exception {

    BufferedInputStream bin = null;
    BufferedOutputStream bout = null;
    try {
      bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
      bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
      int b;
      while ((b = bin.read()) != -1) {
        bout.write(b);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (bin != null) {
        try {
          bin.close();
        } catch (IOException e) {
          throw e;
        } finally {
          if (bout != null) {
            try {
              bout.close();
            } catch (IOException e) {
              throw e;
            }
          }
        }
      }
    }
  }

  public void trywithresource() {
    try (BufferedInputStream bin =
            new BufferedInputStream(new FileInputStream(new File("test.txt")));
        BufferedOutputStream bout =
            new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
      int b;
      while ((b = bin.read()) != -1) {
        bout.write(b);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
